package com.micai.springboot.web;

import com.micai.springboot.dao.UserDao;
import com.micai.springboot.entity.UserEntity;
import com.micai.springboot.vo.UserCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 赵新国 on 2017/8/21.
 */
@RestController
public class UserController {

    @Autowired
    private UserDao userDao;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public void saveUser(@RequestBody UserEntity userEntity) {
        userDao.saveUser(userEntity);
    }

    @RequestMapping(value = "/get",method = RequestMethod.GET)
    public List<UserEntity> getUser(@RequestParam(required = false) String userName) {
        if (userName != null) {
            List<UserEntity> userEntities = new ArrayList<UserEntity>();
            userEntities.add(userDao.findUserByUserName(userName));
            return userEntities;
        } else {
            return userDao.findUserAll();
        }
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
    public int updateUser(@PathVariable("id") String id, @RequestBody UserEntity userEntity) {
        UserEntity entity = userDao.findUserById(id);
        UserEntity entity1 = new UserEntity(entity.getId(),userEntity.getUserName(),userEntity.getPassWord(), userEntity.getPhone());
        return userDao.updateUser(entity1);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<UserEntity> deleteUser(@PathVariable("id") String id) {
        UserEntity userEntity = userDao.findUserById(id);
        if (userEntity == null) {
            return new ResponseEntity<UserEntity>(HttpStatus.NOT_FOUND);
        }
        userDao.deleteUserById(id);
        return new ResponseEntity<UserEntity>(HttpStatus.NO_CONTENT);
    }

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public List<UserEntity> listUser() {
        return userDao.findUserAll();
    }

    @RequestMapping(value = "/count",method = RequestMethod.GET)
    public List<UserCountVo> countUser() {
        return userDao.countUserAll();
    }

}
